<template>
  <div v-if="secondsRemaining > 0">
    <slot :time="formattedTime">{{ formattedTime }}</slot>
  </div>
</template>

<script>
export default {
  name: 'Countdown',
  props: {
    // 来自父组件的剩余时间（秒）
    expireTime: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      secondsRemaining: this.expireTime,
      intervalId: null
    };
  },
  computed: {
    formattedTime() {
      return this.formatTime(this.secondsRemaining);
    }
  },
  methods: {
    startCountdown() {
      this.intervalId = setInterval(() => {
        if (this.secondsRemaining > 0) {
          this.secondsRemaining--;
        } else {
          this.stopCountdown();
        }
      }, 1000); // 每秒执行一次
    },
    stopCountdown() {
      clearInterval(this.intervalId);
      this.$emit('finished'); // 当倒计时结束时触发事件
    },
    formatTime(seconds) {
      const h = Math.floor(seconds / 3600);
      const m = Math.floor((seconds % 3600) / 60);
      const s = seconds % 60;
      return [h, m, s].map(this.padZero).join(':');
    },
    padZero(num) {
      return num.toString().padStart(2, '0');
    }
  },
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    if (this.intervalId) {
      this.stopCountdown();
    }
  }
};
</script>
